package com.huixue.cn.ztej.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huixue.cn.ztej.bean.Results;
import com.huixue.cn.ztej.bean.Role;
import com.huixue.cn.ztej.bean.RoleResource;
import com.huixue.cn.ztej.dao.RoleMapper;
import com.huixue.cn.ztej.dao.RoleResourceDao;
import com.huixue.cn.ztej.utils.SystemContents.API_RETURN_STATUS;


@Service
public class SysRoleService {

	
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private RoleResourceDao roleResourceDao;
	/**
	 * 列出所有角色
	 * @return
	 */
	public Results listRole(int roleId){
		
		
		Map<String, Object> rmap = new HashMap<String, Object>();
		
		
		List<Role> list = roleMapper.listRole(roleId);
		
		rmap.put("rows", list);
		
		Results results = new Results(
				API_RETURN_STATUS.NORMAL.value(),
				API_RETURN_STATUS.NORMAL.desc(),rmap);
		
		return results;
	}
	
	/**
	 * 保存角色
	 * @param role
	 * @return
	 */
	public int addRole(Role role){
		return roleMapper.saveRole(role);
	}
	
	/**
	 * 查找角色
	 * @param role
	 * @return
	 */
	public Role findRole(Role role){
		role  = roleMapper.findRole(role);
		return role;
		
	}
	
	/**
	 * 修改角色
	 * @param role
	 * @return
	 */
	public void udpate(Role role){
		//删除角色对应的Resource
		roleResourceDao.deleteResByRole(role.getRole_id());
		//添加角色对应的Resource
		if(role.getResourceIds()!=null && role.getResourceIds().length()>0){
			String ids = role.getResourceIds();
			String []array = ids.split(",");
			List<RoleResource> list = new ArrayList<RoleResource>();
			for(int i = 0; i<array.length;i++){
				RoleResource roleRes = new RoleResource(role.getRole_id(),Integer.valueOf(array[i]));
				roleResourceDao.insert(roleRes);
			}
			//roleResourceDao.addBatch(list);
		}
		roleMapper.update(role);
	}
	
	
	public Results searchRole(Map<String,Object> searchParams){
		Map<String, Object> rmap = new HashMap<String, Object>();
		List<Role> list = roleMapper.searchRole(searchParams);
		rmap.put("rows", list);
		Results results = new Results(
				API_RETURN_STATUS.NORMAL.value(),
				API_RETURN_STATUS.NORMAL.desc(),rmap);
		return results;
	}
}
